import {
  observable,
  action,
  computed,
} from 'mobx';
import {
  WeaTools
} from 'ecCom';
import moment from 'moment';
import * as API from '../apis/checking';
import * as Util from '../util/index';
import isEmpty from 'lodash/isEmpty';
import {
  WeaTableNew
} from 'comsMobx'
const {
  TableStore
} = WeaTableNew;
import {
  onNewRequest
} from '../util/pulic-func';
import {
  WeaLocaleProvider
} from 'ecCom';
import {message} from 'antd';
const getLabel = WeaLocaleProvider.getLabel;

export class HrmChecking {
  tabDatas = [{
    title: '考勤统计',
    key: "1"
  }, {
    title: '考勤日历',
    key: "2"
  }];
  leftTitle = '人员组织';
  dateTabDatas = [{
    title: '年',
    key: "1"
  }, {
    title: '月',
    key: "2"
  }];
  constructor(props) {
    this.statusList = [{
      name: '全部',
      type: 'ALL',
    }, {
      name: '正常',
      type: 'NORMAL',
    }, {
      name: '迟到',
      type: 'BELATE',
    }, {
      name: '早退',
      type: 'LEAVEEARLY',
    }, {
      name: '旷工',
      type: 'ABSENT',
    }, {
      name: '漏签',
      type: 'NOSIGN',
    }, {
      name: '请假',
      type: 'LEAVE',
    }, {
      name: '出差',
      type: 'EVECTION',
    }, {
      name: '公出',
      type: 'OUTDAYS',
    }, {
      name: '加班',
      type: 'OVERTIME',
    }];
    this.statusList.reverse();
    // this.statusList.forEach((item)=> {
    //   const ic = Util.getIconColor(item.type);
    //   item.icon = ic.icon;
    //   item.color = ic.color;
    //   item.name = ic.name;
    //   if(ic.title){
    //     item.title = ic.title;
    //   }
    // });
  }
  @observable stsType = '';

  @observable hrmId = undefined;
  @observable newWorklist = [];
  @observable visible = false;
  @observable newVisible = false;
  @observable table = new TableStore();
  @observable yearData = {};
  @observable calendarData = {};
  @observable sData = {};
  @observable hrmName = WeaTools.ls.getJSONObj('theme-account') && WeaTools.ls.getJSONObj('theme-account').username || undefined;
  @observable statusActiveType = 'ALL';
  @observable calendarCheckedDay = undefined;
  @observable loading = false;
  @observable tabkey = '1';
  @observable dateTabkey = '2';
  @observable userRoot = undefined;
  @observable pDate = new moment().format('YYYY-MM');
  @observable pDate1 = new moment();
  @observable hasRight = true;
  @observable chartOptions = {
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b}: {c} ({d}%)",
      position: 'right',
    },
    series: [{
      type: 'pie',
      name: getLabel('16732', "出勤统计"),
      radius: ['60%', '80%'],
      avoidLabelOverlap: false,
      label: {
        normal: {
          show: true,
          position: 'center',
          formatter: [
            `{a|${this.count}}`,
            `{b|${this.countTxt}}`
          ].join('\n'),

          rich: {
            a: {
              color: '#484A4D',
              fontSize: 24,
              lineHeight: 24
            },
            b: {
              color: '#666',
              fontSize: 11,
            },
          },
        }
      },
      color: ['#FC4B6C', '#1E88E5'],
      data: []
    }]
  };
  @observable groupitem2 = [];
  @observable groupitem3 = [];
  @observable groupitem4 = [];
  @observable groupitem5 = [];
  @observable wfinfo = [];

  @computed get groupwfinfo() {
    //缓存newWorklist、wfinfo
    const newWorklist = this.newWorklist,
        wfinfo = this.wfinfo,
        arr = [];

    if (newWorklist && wfinfo) {
        newWorklist.forEach(data => {
            const { wfid } = data;

            wfinfo.forEach(info => {
                const { wfbeans } = info;
                const target = wfbeans.find(data => data.id == wfid);
                if (target) {
                    const { typeId } = target;
                    const exist = arr.find(data => data.typeId == typeId);
                    if (exist) {
                        exist.wfs.push(data);
                    }else{
                        arr.push({
                          typeId,
                          wfs:[data],
                          ...info
                        })
                    }
                }
            })
        })
    }

    return arr;

}

  @action getStatusList = () => {
    let arr = [];
    this.statusList.forEach((item) => {
      const ic = Util.getIconColor(item.type);
      arr.push({ ...ic,
        type: item.type
      });
      // item.icon = ic.icon;
      // item.color = ic.color;
      // item.name = ic.name;
      // if(ic.title){
      //   item.title = ic.title;
      // }
    });
    return arr;
  }

  @observable overTimeTabDatas = [];
  @observable overTimeTabkey = '1';

  @action
  handlerNewWorkflow(item) {
    onNewRequest(item);
    this.newVisible = false;
  }

  @action
  updateVisible(v) {
    this.visible = v;
  }

  @action
  updateNewVisible(v) {
    this.newVisible = v;
  }

  @action
  updateStsType(v) {
    this.stsType = v;
  }

  @action
  handlerStatusClick(type) {
    this.statusActiveType = type;
  }

  @action
  updateCalendarCheckedDay(v) {
    this.calendarCheckedDay = v;
    this.getHrmKQSignInfo();
  }

  @action
  changeTabHandler(key) {
    this.tabkey = key;
    this.calendarCheckedDay = undefined;
    this.statusActiveType = 'ALL';
  }
  @action
  changeDateTabHandler(key) {
    if (this.pDate) {
      if (key == '1') {
        this.pDate = new moment().format('YYYY');
      } else {
        this.pDate = new moment().format('YYYY-MM');
      }
    }
    this.pDate1 = new moment();
    this.dateTabkey = key;
    this.calendarCheckedDay = undefined;
    this.statusActiveType = 'ALL';
  }

  @action
  updateDateTabkey(key) {
    this.dateTabkey = key;
  }

  @action
  changeDateHandler(v) {
    this.pDate = v;
    if (v.length == 4)
      this.pDate1 = new moment().year(v);
    this.statusActiveType = 'ALL';
    this.calendarCheckedDay = undefined;
  }
  @action
  init() {
    this.tabkey = '1';
    this.dateTabkey = '2';
    this.pDate = new moment().format('YYYY-MM');
    this.hrmId = undefined;
    this.hrmName = WeaTools.ls.getJSONObj('theme-account') && WeaTools.ls.getJSONObj('theme-account').username || undefined;
    this.userRoot = undefined;
  }

  @action
  updateUserRoot(data) {
    this.userRoot = data;
  }

  @action
  updateHrmId(v) {
    this.hrmId = v;
  }

  @action
  updateHrmName(v) {
    this.hrmName = v || WeaTools.ls.getJSONObj('theme-account') && WeaTools.ls.getJSONObj('theme-account').username || undefined;
  }

  @action
  getTableData() {
    let params = {};
    if (this.hrmId) params.resourceId = this.hrmId;
    if (this.pDate) params.typevalue = this.pDate;
    params.type = this.dateTabkey;
    params.kqtype = this.stsType;
    this.table = new TableStore();

    if (this.stsType === 'OVERTIME') {
      API.getKQReportDetail({
        typeselect: 6,
        ...this.getDateScope(this.pDate),
        viewScope: 3,
        resourceId: this.hrmId,
        source:"isMyKq",
        isNoAccount: 0,
        attendanceSerial: '',
        type: 'overtimeTotal',
        tabKey: this.overTimeTabkey,
        reportType: 'month'
      }).then(datas => {
        const {
          sessionkey,
          status
        } = datas;

        if (status === '1') {
          this.table.getDatas(sessionkey, 1);
        } else {
          message.warning(datas.message);
        }
      })
    } else {
      API.getTableData(params).then((datas) => {
        this.table.getDatas(datas.sessionkey, 1);
      })
    }
  }

  getDateScope = (date) => {
    if (date) {
     return{
      fromDate:`${date}-01`,
      toDate:`${date}-31`
     }
    }else{
      return {}
    }
   
  }

  @action
  getData(cb) {
    let params = {};
    if (this.hrmId) params.resourceId = this.hrmId;
    if (this.pDate) params.typevalue = this.pDate;
    params.loaddata = "1";
    params.type = this.dateTabkey;
    this.loading = true;
    if (this.tabkey == '1') {
      API.getKQReport(params).then((datas) => {
        if (datas.status == '1') {
          this.hasRight = true;
          if (datas.groupitem1) {
            this.chartOptions.series[0].name = getLabel('16732', "出勤统计");
            this.chartOptions.series[0].label.normal.formatter = [
              `{a|${parseFloat(datas.groupitem1.value)}}`,
              `{b|${datas.groupitem1.name}}`
            ].join('\n')
            datas.groupitem1.items.forEach((i) => {
              i.value = parseFloat(i.value);
            })
            this.chartOptions.series[0].data = datas.groupitem1.items;
            const {
              items
            } = datas.groupitem1;
            let total = 0;
            items.forEach(item => {
              const {
                value
              } = item;
              total += parseFloat(value);
            });
            if (total === 0) {
              this.chartOptions.series[0].color = ['#c5c5c5','#c5c5c5'];
            } else {
              this.chartOptions.series[0].color = ['#FC4B6C', '#1E88E5'];
            }
          }
          this.groupitem2 = (datas.groupitem2 && datas.groupitem2.items) || [];
          this.groupitem2.forEach((item) => {
            const ic = Util.getIcon(item.type);
            item.icon = ic.icon;
            item.color = ic.color;
          })
          this.groupitem3 = (datas.groupitem3 && datas.groupitem3.items) || [];
          this.groupitem4 = (datas.groupitem4 && datas.groupitem4.items) || [];
          this.groupitem5 = (datas.groupitem5 && datas.groupitem5.items) || [];
          cb && cb();
        } else {
          this.hasRight = false;
        }
        this.loading = false;
      })
    } else {
      API.getKQCarendarReport(params).then((datas) => {
        if (datas.status == '1') {
          if (this.dateTabkey == '1') {
            this.yearData = datas.result;
          } else {
            this.calendarData = datas.result;
          }
          this.hasRight = true;
        } else {
          this.hasRight = false;
        }
        this.loading = false;
      })
    }
  }

  @action getHrmKQSignInfo = () => {
    let params = {};
    let day;

    if (this.calendarCheckedDay.toString().length < 2) {
      day = `0${this.calendarCheckedDay}`
    } else {
      day = this.calendarCheckedDay;
    }
    if (this.hrmId) params.resourceId = this.hrmId;
    if (this.pDate) params.date = `${this.pDate}-${day}`;
    API.getHrmKQSignInfo(params).then((datas) => {
      const {
        data
      } = datas;

      this.sData = data;
    })
  }

  @action
  getHrmNewWorkflwList(params = {}) {
    API.getHrmNewWorkflwList(params).then((datas) => {
      this.newWorklist = datas.result;
    })
  }

  @action
  getwfinfo = () => {
    const params = {
      needall: 1,
      menuIds: "1,12",
      tabkey: 1
    };
     API.getwfinfo(params).then(res => {
      const { datas } = res;

      this.wfinfo = datas;
    })
  }

  @computed get hasLeaveInfo() {
    return this.groupitem5.length > 0
  }

  dialogHeight = 790;

  kqDetailDialogHeight = 500;

  setDialogHeight = (h) => {
    this.kqDetailDialogHeight = h;
  }

  ABSENCEDIALOG = {
    icon: 'icon-coms-hrm',
    iconBgcolor: '#217346',
    onCancel: () => {
      this.absenceDialog.visible = false
    },
    onChangeHeight: (h) => {
      this.dialogHeight = h;
    },
    moreBtn: {
      datas: []
    },
    style: {
      width: 800,
      height: 790
    },
    title: getLabel(507088, '未出勤明细')
  }

  @observable absenceDialog = {
    visible: false,
    loading: false,
  }

  @observable absenceDetail = {
    absenceDay: 0,
    types: [],
    details: [],
  };

  @action openAbsenceDialog = () => {
    this.absenceDialog.visible = true;
    this.getHrmKQReportDetialInfo();
  }

  @action getHrmKQReportDetialInfo = () => {
    const params = {
      type: this.dateTabkey,
      kqtype: 'leaveDays'
    };

    this.absenceDialog.loading = true;
    if (this.hrmId) {
      Object.assign(params, {
        resourceId: this.hrmId
      });
    }
    if (this.pDate) {
      Object.assign(params, {
        typevalue: this.pDate
      });
    }

    API.getHrmKQReportDetialInfo(params).then(datas => {
      ['absenceDay', 'types', 'details'].forEach((v, index) => {
        this.absenceDetail[v] = datas[v];
        this.absenceDialog.loading = false;
      });
    })
  }

  getOverTimeTabDatas  =() => {
    return new Promise( (resolve,reject)=>{
      API.getTab({
        type: 'overtimeTotal'
      }).then(datas=>{
        const {status,tabs} = datas;
        if (status === '1') {
          this.overTimeTabDatas = tabs;
          this.overTimeTabkey = tabs[0].key;

          resolve();
        }else{
          message.warning(datas.message);
          reject();
        }
      })
    } )
  }

  handleOverTimeTabClick = (key) => {
    this.overTimeTabkey = key;

    this.getTableData();
  }


}